package edu.hcmus.sow.web.user;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import edu.hcmus.sow.dao.UserDAO;
import edu.hcmus.sow.domain.User;
import edu.hcmus.sow.service.UserService;

@Controller
public class UserController {

   @Autowired
   private UserDAO userDAO;

   @Autowired
   private UserService userService;

   /**
    * Show all User entities
    * 
    */
   @RequestMapping("/listUsers")
   public ModelAndView listUsers() {
      ModelAndView mav = new ModelAndView();

      mav.addObject("users", userDAO.findAll());

      mav.setViewName("listUsers");

      return mav;
   }

   /**
    * Create a new User entity
    * 
    */
   @RequestMapping("/newUser")
   public ModelAndView newUser() {
      ModelAndView mav = new ModelAndView();

      mav.addObject("user", new User());
      mav.addObject("newFlag", true);
      mav.setViewName("editUser");

      return mav;
   }

   /**
    * Save an existing User entity
    * 
    */
   @RequestMapping("/saveUser")
   public String saveUser(@ModelAttribute User user) {
      userService.saveUser(user);
      return "forward:/listUsers";
   }

   /**
    * Edit an existing User entity
    * 
    */
   @RequestMapping("/editUser")
   public ModelAndView editUser(@RequestParam Integer idKey) {
      ModelAndView mav = new ModelAndView();

      mav.addObject("user", userDAO.findById(idKey));
      mav.setViewName("editUser");

      return mav;
   }
}
